/**************************************************************************/
/*                                                                        */
/*  System  Name :  ICIM                                                  */
/*                                                                        */
/*  Description  :  Product Management                                    */
/*                                                                        */
/*  MODIFICATION HISTORY                                                  */
/*    Date     Ver     Name          Description                          */
/* ---------- ----- ----------- ----------------------------------------- */
/* 2017/05/25 N0.00   meijiao.chen      Initial release                   */
/*                                                                        */
/**************************************************************************/
$(document).ready(function() {
    var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_FBPBISOPE	 : 'FBPBISOPE',
        T_FBPBISTOL  : 'FBPBISTOL',
        T_FBPBISPTH  : 'FBPBISPTH',
        T_FIPINQBOX  : 'FIPINQBOX',
        T_FDPAPLYWO  : "FDPAPLYWO",
        T_FBPMDLDEF  : "FBPMDLDEF",
        T_FPPWHSOPE  : "FPPWHSOPE",
        T_FPPUPKCLM  : "FPPUPKCLM",
        T_FPPMOVEOUT : "FPPMOVEOUT",
        T_FPPUPKCLM : "FPPUPKCLM",
        DISABLED_ATTR : {
            'disabled' : true
        },
        ENABLED_ATTR : {
            'disabled' : false
        }
    };
    var domObj = {

        $query_dense_btn   : $("#query_dense_btn"),
        $query_box_btn     : $("#query_box_btn"),
        $prdMoveInBox_btn  : $("#prdMoveInBox_btn"),
        $moveOut_btn       : $("#moveOut_btn"),

        tempProdListDiv : $("#tempProdListDiv"),
        tempProdListGrd : $("#tempProdListGrd"),
        tempProdListPg : "#tempProdListPg",

        $denseIdTxt          :      $("#denseIdTxt"),
        $denseMtrlIdTxt      :      $("#denseMtrlIdTxt"),
        $denseMtrlCusTxt     :      $("#denseMtrlCusTxt"),
        $prodThicknessTxt    :      $("#prodThicknessTxt"),
        $prodQtyTxt          :      $("#prodQtyTxt"),

        $woCateSel	      :         $("#woCateSel"),
        $woIdSel          :         $("#woIdSel"),
        $mdlIdTxt         :         $("#mdlIdTxt"),
        $pathIdTxt        :         $("#pathIdTxt"),
        $woCntTxt         :         $("#woCntTxt"),

        $opeIdSel     :		$("#opeIdSel"),
        $toolIdSel    :		$("#toolIdSel"),
        $portIdSel    :		$("#portIdSel"),
        $boxIdTxt     :		$("#boxIdTxt"),
        $maxCntTxt    :		$("#maxCntTxt"),
        $curCntTxt    :     $("#curCntTxt"),

        $remarkTxt    :     $("#remarkTxt"),

        dialogs : {
            $switchDialog : $("#switchDialog"),
            $switchkDialog_prdQtyTxt : $("#switchkDialog_prdQtyTxt"),
            $switchDialog_sureBtn : $("#switchDialog_sureBtn")
        }

    };
    var iniGridInfo = function(){
        var tempProdListCM = [
            {name: 'slot_no',   		index: 'slot_no',   	label: SLOT_NO_TAG    , 		width: 100},
            {name: 'prd_seq_id', 		index: 'prd_seq_id',	label: SHEET_ID_TAG    , 		width: 200},
            {name: 'prd_thickness',		index: 'prd_thickness', label: THICKNESS_TAG,			width: 100},
            {name: 'mtrl_box_id_fk',    index: 'mtrl_box_id_fk',label: PPBOX_ID_TAG  , 			width: 160},
            {name: 'box_id_fk',     	index: 'box_id_fk',   	label: MOVE_OUT_PPBOX_ID_TAG  , width: 160},
            {name: 'mdl_id_fk',     	index: 'mdl_id_fk',   	label: PRODUCT_ID_TAG  , 		width: 160},
            {name: 'wo_id_fk',     		index: 'wo_id_fk',   	label: WO_ID_TAG  , 			width: 160},
            {name: 'evt_usr',     		index: 'evt_usr',   	label: EVT_USR  , 				width: 100},
            {name: 'evt_timestamp',     index: 'evt_timestamp', label: EVT_TIMESTAMP  , 		width: 200}

        ];
        domObj.tempProdListGrd.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            height:200,
            width:domObj.tempProdListDiv.width(),
            shrinkToFit:true,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            loadonce:true,
            fixed:true,
            viewrecords:true,
//            multiselect : true,
            pager : domObj.tempProdListPg,
            colModel: tempProdListCM,
            onSelectRow: function(id){}
        });

    };
    var toolFunc = {
        queryDense_func:function(){
            var denseIdTxt = domObj.$denseIdTxt.val();
            if(!denseIdTxt){
                showErrorDialog("","请输入DenseBoxID！")
                return;
            }
            var inObj = {
                trx_id : VAL.T_FPPWHSOPE,
                action_flg : "Q",
                iary : [{
                    mtrl_box_id : denseIdTxt
                }]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                oary = outObj.oary[0];
                if (!oary) {
                    showErrorDialog("","不存在此Dense！");
                    return false;
                }
                var ppbox_stat = oary.ppbox_stat.trim();
                if( null == ppbox_stat || ppbox_stat != 'OUT'){
                    showErrorDialog("","状态不正确！");
                    return false;
                }
                var tlQty = Number(oary.prd_tl_qty.trim());
                var actQty = Number(oary.prd_act_qty.trim());

                if(tlQty < actQty){
                    showErrorDialog("","数量不正确！");
                    return false;
                }
                domObj.$denseIdTxt.val(denseIdTxt);
                domObj.$denseMtrlIdTxt  .val(oary.mtrl_prod_id_fk.trim());
                domObj.$denseMtrlCusTxt .val(oary.cus_id_fk.trim());
                domObj.$prodThicknessTxt.val(oary.mtrl_thickness.trim());
                domObj.$prodQtyTxt      .val(oary.prd_act_qty.trim());
            }

        },
        getBoxInf:function(box_id){
            var inObj,outObj;
            var tool_id = $("#toolIdSel option:selected").val();
            if(box_id == ""){
                showErrorDialog("","请输入转入箱号！");
                return false;
            }
            domObj.tempProdListGrd.clearGridData();
            inObj={
                trx_id : VAL.T_FIPINQBOX,
                action_flg : "Q",
                box_id : box_id,
            }
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                if(outObj.box_stat != "INPR" && outObj.box_stat != "EMPT"){
                    showErrorDialog("","箱子状态不正确["+outObj.box_stat+"]，只可以操作空卡匣或者在制程中的卡匣！");
                    return false;
                }
                if(outObj.box_stat == "INPR"){
                    if(outObj.oary[0].cr_tool_id_fk.trim() != tool_id){
                        showErrorDialog("","转入箱号对应设备代码["+outObj.oary[0].cr_tool_id_fk.trim()+
                            "]与所选设备代码["+tool_id+"]不符!");
                        return false;
                    }
                }
                if(outObj.box_cate !="WCST"){
                    showErrorDialog("","转入卡匣的类型["+outObj.box_cate+"]不正确，必须为WCST!");
                    return false;
                }
                domObj.$maxCntTxt.val(outObj.max_cnt);
                domObj.$curCntTxt.val(outObj.prd_qty);
                setGridInfo(outObj.oary, "#tempProdListGrd");

            }
        },
        iniWoCateSel : function(){
            comAddValueByDataCateFnc("#woCateSel","WOCT","data_ext","data_desc",true);
        },
        iniPortSel: function(portObj,toolObj){
            portObj.empty();
            var toolSelVal = toolObj.find("option:selected").val();
            var inObj, outObj;
            var iary = {
                tool_id : toolSelVal,
                port_typ:"U"
            }
            inObj = {
                trx_id    : VAL.T_FBPBISTOL,
                action_flg: 'I',
                iary	  : [iary]
            }
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                SelectDom.addSelectArr(portObj, outObj.oaryB, "port_id","port_id","",true);
            }
            portObj.select2({
                theme : "bootstrap"
            });

        },
        iniToolSel: function(toolObj,opeObj){
            toolObj.empty();
            var opeSelVal = opeObj.find("option:selected").val();
            var tool_run_mode ;
            if(opeSelVal){
                var ope_id = opeSelVal.split("@")[0];
                var ope_ver = opeSelVal.split("@")[1];
            }else{
                return;
            }
            var inTrxObj ={
                trx_id     : VAL.T_FBPBISOPE,
                action_flg : 'Q'        ,
                iary       :[{
                    ope_id	: ope_id,
                    ope_ver : ope_ver
                }]
            };
            var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if(  outTrxObj.rtn_code == VAL.NORMAL ) {
                oary = outTrxObj.oary[0];
                if (!oary) {
                    return ;
                }
                tool_run_mode = oary.tool_run_mode
            }
            var inObj, outObj;
            var item = "tool_id";
            var iary = {
                tool_run_mode : tool_run_mode,
                unit_typ       : "MAIN"
            };
            inObj = {
                trx_id      : VAL.T_FBPBISTOL,
                action_flg  : 'H',
                iary		 : [iary]
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                SelectDom.addSelectArr(toolObj, outObj.oary, "tool_id","tool_id","",true);
            }
            toolObj.select2({
                theme : "bootstrap"
            });
//            toolFunc.iniPortSel(domObj.$portIdSel,domObj.$toolIdSel);
        },
        setOpeSelectDate : function(dataCnt, oary, selVal, selVal2, selTxt, queryObj,emptySel){
            var i, realCnt;

            queryObj.empty();
            realCnt = parseInt( dataCnt, 10);
            if (emptySel) {
                queryObj.append("<option value=''></option>");
            }
            for (var i=0;i<realCnt;i++) {
                queryObj.append("<option value = "+oary[i][selVal]+"@" + oary[i][selVal2] +">"+ oary[i][selTxt]+"</option>");
            }
            queryObj.select2({
                theme : "bootstrap"
            });
            toolFunc.iniToolSel(domObj.$toolIdSel,domObj.$opeIdSel);
        },
        setPostInfo :function(path_id,path_ver){
            var iaryB = {};
            iaryB.path_id_fk  = path_id;
            iaryB.path_ver_fk = path_ver;
            var inObj = {
                trx_id	   : VAL.T_FBPBISPTH,
                action_flg : "I",
                iaryB      : [iaryB]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                var oaryBList = outObj.oaryB;
                var tool_run_mode = 'UPK';
                var ope_id, ope_ver,inTrxObj,outTrxObj,oaryA= new Set(),oaryB={};
                for (var i = 0; i < oaryBList.length; i++) {
                    ope_id = oaryBList[i].cr_ope_id_fk;
                    ope_ver = oaryBList[i].cr_ope_ver_fk;
                    ope_no = oaryBList[i].cr_ope_no;
                    inTrxObj= {
                        trx_id : VAL.T_FBPBISOPE,
                        action_flg: 'Q',
                        iary : [{
                            ope_id:ope_id,
                            ope_ver:ope_ver
                        }]
                    }
                    outTrxObj = comTrxSubSendPostJson(inTrxObj);
                    if (outTrxObj.rtn_code === VAL.NORMAL) {
                        if (outTrxObj.tbl_cnt > 0) {
                            //Get Operation except UPK
                            if(outTrxObj.oary[0].tool_run_mode == tool_run_mode){
                                oaryA.add(outTrxObj.oary[0]);
                            }
                        }

                    }
                }

                toolFunc.setOpeSelectDate(oaryA.length, oaryA, "ope_id", "ope_ver", "ope_id", domObj.$opeIdSel,true);
            }
        },
        setWoInfo : function(){
            var mtrl_id = domObj.$denseMtrlIdTxt.val();
            if(!mtrl_id){
                showErrorDialog("","来料料号不能为空！");
                return false;
            }
            var cus_id  = domObj.$denseMtrlCusTxt.val();
            if(!cus_id){
                showErrorDialog("","来料厂商不能为空！");
                return false;
            }
            var prod_thickness = domObj.$prodThicknessTxt.val();
            if(!prod_thickness){
                showErrorDialog("","玻璃厚度不能为空！");
                return false;
            }
            var wo_cate = domObj.$woCateSel.find("option:selected").val();
            if(wo_cate == ""){
                domObj.$mdlIdTxt.val("");
                domObj.$woIdSel.val("");
                domObj.$pathIdTxt.val("");
                domObj.$woCntTxt.val("");
                return false;
            }
            domObj.$opeIdSel.empty();
            var inObj = {
                trx_id : VAL.T_FDPAPLYWO,
                action_flg : "I",
                iary : [{
                    mtrl_prod_id_fk : mtrl_id,
                    cus_id_fk 		 :cus_id,
                    from_thickness  :prod_thickness,
                    wo_cate 		 : wo_cate
                }]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                domObj.$mdlIdTxt.val("");
                domObj.$woIdSel.val("");
                domObj.$pathIdTxt.val("");
                domObj.$woCntTxt.val("");
                oary = outObj.oary[0];
                if (!oary) {
                    return;
                }
                var mdl_id_fk = oary.mdl_id_fk.trim();
                domObj.$woIdSel.val(oary.wo_id.trim());
                domObj.$mdlIdTxt.val(mdl_id_fk);
                domObj.$woCntTxt.val( parseInt(oary.pln_prd_qty,10)-parseInt(oary.rl_prd_qty,10) );

                var inTrxObj ={
                    trx_id     : VAL.T_FBPMDLDEF,
                    action_flg : 'Q'        ,
                    iary       :[{
                        mdl_id	: mdl_id_fk
                    }]
                };
                var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
                if(  outTrxObj.rtn_code == VAL.NORMAL ) {
                    oary = outTrxObj.oary[0];
                    if(!oary){
                        return;
                    }
                    domObj.$pathIdTxt.val(oary.path_id_fk);
                    toolFunc.setPostInfo(oary.path_id_fk,oary.path_ver_fk);
                }
            }
        },
        switchDialog : {
            switchShowFnc : function() {
                domObj.dialogs.$switchDialog.modal({
                    backdrop : true,
                    keyboard : false,
                    show : false
                });

                domObj.dialogs.$switchDialog_sureBtn.unbind('click');
                domObj.dialogs.$switchDialog_sureBtn.bind('click', btnFunc.switchToBox);
                domObj.dialogs.$switchkDialog_prdQtyTxt.val("");
                domObj.dialogs.$switchkDialog_prdQtyTxt.focus();
                domObj.dialogs.$switchDialog.modal("show");
            }
        },
        iniOpeProc:function () {
            var iary = {
                tool_run_mode : "UPK"
            };
            inObj = {
                trx_id      : VAL.T_FBPBISOPE,
                action_flg  : 'Q',
                iary		 : [iary]
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                toolFunc.setOpeSelectDate(outObj.oary.length, outObj.oary, "ope_id", "ope_ver", "ope_id", domObj.$opeIdSel,true);
            }
            domObj.$opeIdSel.select2({
                theme : "bootstrap"
            });
        }
    };
    var btnFunc={
        switchToBox:function(){
            var inObj, outObj;
            var ope_id, ope_ver, tool_id, port_id;
            var box_id, mtrl_box_id, wo_id;
            var prd_qty=0;
            box_id = domObj.$boxIdTxt.val();
            mtrl_box_id = domObj.$denseIdTxt.val();
            wo_id = domObj.$woIdSel.val();
            var ope_info = domObj.$opeIdSel.val();
            ope_info_ary = ope_info.split("@");
            ope_id = ope_info_ary[0];
            ope_ver = ope_info_ary[1];
            tool_id = domObj.$toolIdSel.val();
            port_id = domObj.$portIdSel.val();
            prd_qty = domObj.dialogs.$switchkDialog_prdQtyTxt.val();
            domObj.dialogs.$switchDialog.modal("hide");
            if(prd_qty == "" || prd_qty == 0){
                showErrorDialog("","请正确输入转入的玻璃数量！");
                return false;
            }
            inObj = {
                trx_id : VAL.T_FPPUPKCLM,
                action_flg : "S",
//	        	evt_usr : VAL.EVT_USER,
                evt_usr : "CMJ",
                box_id : box_id,
                mtrl_box_id : mtrl_box_id,
                ope_id : ope_id,
                ope_ver : ope_ver,
                tool_id : tool_id,
                port_id : port_id,
                wo_id : wo_id,
                prd_qty : prd_qty,
                opi_ope_flg :"Y"
            }
            var  outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                toolFunc.getBoxInf(box_id);
                toolFunc.queryDense_func();
            }
        },
        switchToBoxBefore:function(){
            var ope_id, ope_ver, tool_id, port_id;
            var box_id, mtrl_box_id, wo_id;
            var cur_prd_qty="";
            box_id = domObj.$boxIdTxt.val();
            cur_prd_qty = domObj.$curCntTxt.val();
            mtrl_box_id = domObj.$denseIdTxt.val();
            wo_id = domObj.$woIdSel.val();
            var ope_info = domObj.$opeIdSel.val();
            ope_info_ary = ope_info.split("@");
            ope_id = ope_info_ary[0];
            ope_ver = ope_info_ary[1];
            tool_id = domObj.$toolIdSel.val();
            port_id = domObj.$portIdSel.val();
            domObj.dialogs.$switchDialog.modal("hide");
            if(!box_id){
                showErrorDialog("","请输入卡匣代码，并获取卡匣信息！");
                return false;
            }
            if(!cur_prd_qty){
                showErrorDialog("","请获取卡匣信息！");
                return false;
            }
            if(!ope_id){
                showErrorDialog("","请选择站点！");
                return false;
            }
            if(!tool_id){
                showErrorDialog("","请选择设备代码！");
                return false;
            }
            if(!port_id){
                showErrorDialog("","请选择设备端口号！");
                return false;
            }
            toolFunc.switchDialog.switchShowFnc();
        },
        moveOutFunc:function(){
            var ope_id, ope_ver, tool_id, port_id;
            var box_id, mtrl_box_id, wo_id;
            var sht_ope_msg = "";
            box_id = domObj.$boxIdTxt.val();
            cur_prd_qty = domObj.$curCntTxt.val();
            mtrl_box_id = domObj.$denseIdTxt.val();
            wo_id = domObj.$woIdSel.val();
            var ope_info = domObj.$opeIdSel.val();
//	        	ope_info_ary = ope_info.split("@");
//	            ope_id = ope_info_ary[0];
//	            ope_ver = ope_info_ary[1];
            tool_id = domObj.$toolIdSel.val();
            port_id = domObj.$portIdSel.val();
            sht_ope_msg = domObj.$remarkTxt.val();
            if(!sht_ope_msg){
                showErrorDialog("","请输入出账备注信息！");
                return false;
            }
            inObj = {
                trx_id  : VAL.T_FPPMOVEOUT,
//                evt_usr : VAL.EVT_USER,
                evt_usr : "CMJ",
                box_id  : box_id,
                mtrl_box_id : mtrl_box_id,
                tool_id : tool_id,
                port_id : port_id,
                sht_ope_msg : sht_ope_msg,
                opi_ope_flg :"Y"
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                showSuccessDialog("出账成功");
                domObj.tempProdListGrd.clearGridData();
                domObj.$boxIdTxt.val("");
                domObj.$curCntTxt.val("");
                domObj.$maxCntTxt.val("");
                domObj.$remarkTxt.val("");
            }
        }
    }
    var iniContorlData = function(){
        $("input").val("");
        $("textarea").val("");
        toolFunc.iniWoCateSel();
        domObj.$woCateSel.change(function(){
            toolFunc.setWoInfo();
        });
    };
    var iniButtonAction = function(){
        domObj.$query_dense_btn.click(function(){
            // iniContorlData();
            toolFunc.queryDense_func();
        });
        domObj.$denseIdTxt.bind('keyup',function(event){
            if(event.keyCode==13){
                toolFunc.queryDense_func();
            }
        });
        domObj.$opeIdSel.change(function(){
            toolFunc.iniToolSel(domObj.$toolIdSel,domObj.$opeIdSel);
        });
        domObj.$toolIdSel.change(function(){
            toolFunc.iniPortSel(domObj.$portIdSel,domObj.$toolIdSel);
        });
        domObj.$boxIdTxt.bind('keyup',function(event){
            if(event.keyCode==13){
                var box_id = domObj.$boxIdTxt.val().trim();
                toolFunc.getBoxInf(box_id);
            }
        });
        domObj.$prdMoveInBox_btn.click(function(){
            btnFunc.switchToBoxBefore();
        });
        domObj.$moveOut_btn.click(function(){
            btnFunc.moveOutFunc();
        });
        domObj.$query_box_btn.click(function(){
            var box_id = domObj.$boxIdTxt.val().trim();
            toolFunc.getBoxInf(box_id);
        });

    };
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        iniContorlData();
        toolFunc.iniOpeProc();
    };
    initializationFunc();
    //模态框拖动
    $(".modal-content").draggable();
    //表格自适应
    function resizeFnc(){
        var offsetBottom, grdDivWidth;
        grdDivWidth = $("#divTop").width();
        offsetBottom = $(window).height() - $("#tempProdListDiv").offset().top;

        $("#tempProdListDiv").width(grdDivWidth*0.98);
        $("#tempProdListDiv").height(offsetBottom*0.99);
        $("#tempProdListGrd").setGridWidth(grdDivWidth*0.97);
        $("#tempProdListGrd").setGridHeight(offsetBottom*0.95-51);
    };
    resizeFnc();
    $(window).resize(function() {
        resizeFnc();
    });

});
